package com.example.webmodule.listener;

import com.alibaba.fastjson2.JSON;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.shaded.com.google.common.collect.Lists;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.example.webmodule.entity.ServiceInfo;
import com.example.webmodule.model.ServiceInterface;
import com.example.webmodule.service.ServiceInterfaceService;
import com.example.webmodule.strategy.RegistrySelectStrategy;
import com.example.webmodule.strategy.RegistryStrategyFactory;
import com.example.webmodule.util.ConvertVoUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @ClassName EY-ServiceInfoEventListener
 * @Description com.example.webmodule.listener
 * @Author menyj
 * @Date 2025/3/19
 **/
@Slf4j
@Component
public class InstanceEventListener extends AbstractUpdateTemplate implements ApplicationListener<InstanceEvent> {

    @Autowired
    private ServiceInterfaceService serviceInterfaceService;

    @Autowired
    private RegistryStrategyFactory registryStrategyFactory;

    public InstanceEventListener(ServiceInterfaceService serviceInterfaceService) {
        super(serviceInterfaceService);
    }

    @Override
    public void onApplicationEvent(InstanceEvent event) {

        log.info("InstanceEventListener handle event start = {}", JSON.toJSONString(event));
        String serviceId = event.getServiceId();
        update(serviceId, event);
        /**
         * nacos返回的实例信息
         * [
         *        {
         * 		"clusterName": "DEFAULT",
         * 		"enabled": true,
         * 		"ephemeral": true,
         * 		"healthy": true,
         * 		"instanceHeartBeatInterval": 5000,
         * 		"instanceHeartBeatTimeOut": 15000,
         * 		"instanceId": "192.168.56.1#8090##default@@module-a",
         * 		"ip": "192.168.56.1",
         * 		"ipDeleteTimeout": 30000,
         * 		"metadata": {
         * 			"management.endpoints.web.base-path": "/ey/actuator",
         * 			"preserved.register.source": "SPRING_CLOUD"
         *        },
         * 		"port": 8090,
         * 		"serviceName": "default@@module-a",
         * 		"weight": 1.0
         *    }
         * ]
         */
    }

    /**
     * 通过 serviceId 获取 数据库中当前已有的接口信息
     * @param serviceId
     * @return
     */
    @Override
    public List<ServiceInterface> getUpdateBeforeList(String serviceId) {
        LambdaQueryWrapper<ServiceInterface> wrapper = Wrappers.lambdaQuery(ServiceInterface.class)
                .eq(ServiceInterface::getServiceId, serviceId);
        List<ServiceInterface> beforeUpdateList = serviceInterfaceService.list(wrapper);
        return beforeUpdateList;
    }

    /**
     * 从事件中获取nacos返回的实例信息，并拼装成接口数据信息
     * @param event
     * @return
     */
    @Override
    public List<ServiceInterface> getNeedUpdateList(ApplicationEvent event) {
        InstanceEvent instanceEvent = (InstanceEvent) event;
        List<Instance> instanceList = instanceEvent.geInstanceList();
        RegistrySelectStrategy registrySelectStrategy = registryStrategyFactory.getStrategy();
        List<ServiceInterface> allNoticeServiceInterfaceList = Lists.newArrayList();
        for (Instance instance: instanceList) {
            ServiceInfo serviceInfo = ConvertVoUtil.convertInstaceToServiceInfo(instance);
            serviceInfo.setOpenApiList(registrySelectStrategy.fetchApiPaths(serviceInfo));
            allNoticeServiceInterfaceList.addAll(ConvertVoUtil.convertServiceInfoToServiceInterfaceList(serviceInfo));
        }
        return allNoticeServiceInterfaceList;
    }
}
